import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {NzMessageService} from 'ng-zorro-antd';
import * as _ from 'underscore';

@Component({
  selector: 'app-synchronization',
  templateUrl: './synchronization.component.html',
  styleUrls: ['./synchronization.component.scss']
})
export class SynchronizationComponent implements OnInit {
  envId;
  tableId;
  list = [];
  model;
  sql = '';
  diffLoading = false;
  executeLoading = false;

  constructor(
    private http: HttpClient,
    private message: NzMessageService,
  ) {
  }

  ngOnInit() {
    this.http.get<any[]>('/api/environment').subscribe(res => {
      this.list = res;
    });
  }

  changeEnvironment(envId: any) {
    this.model = _.find(this.list, o => {
      return o[`id`] === envId;
    });
  }

  diff() {
    this.sql = '';
    this.diffLoading = true;
    this.http.get<string>('/api/environment/diff/' + this.envId + '/' + this.tableId).subscribe(res => {
      this.sql = res[`data`];
      this.diffLoading = false;
    }, err => {
      this.message.create('error', err.error.message);
      this.diffLoading = false;
    });
  }

  update() {
    this.executeLoading = true;
    this.http.get('/api/environment/update/' + this.envId + '/' + this.tableId).subscribe(() => {
      this.message.create('success', '更新成功');
      this.sql = '';
      this.executeLoading = false;
    }, err => {
      this.message.create('error', `更新失败，${err.error.message}`);
      this.executeLoading = false;
    });
  }
}
